﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using IceDog.EFCore.ContosoUniversity.Models;

namespace IceDog.EFCore.ContosoUniversity.Pages.Students
{
    public class CreateModel : PageModel
    {
        private readonly IceDog.EFCore.ContosoUniversity.Data.SchoolContext _context;

        public CreateModel(IceDog.EFCore.ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            Student = new Student
            {
                FirstMidName = "Tom",
                LastName = "Howard",
                EnrollmentDate = DateTime.Now.AddYears(-1)
            };
            return Page();
        }

        [BindProperty]
        public Student Student { get; set; }//TryUpdateModelAsync第二个参数找的是这个

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            //--这种是从数据存储到数据库的时候选择只需要的属性
            var emptyStudent = new Student();
            //此处的目的是限定仅仅需要的字段，不需要的字段就算是有属性也不用
            var result = await TryUpdateModelAsync(emptyStudent, "student"/* 用于查找值的前缀，该自变量不区分大小写*/,
                s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate);
            if (result)
            {
                _context.Student.Add(emptyStudent);
                await _context.SaveChangesAsync();
                return RedirectToPage("./Index");
            }
            return null;
        }
    }
}